/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.untar;

import cn.ac.iie.di.global.GlobalParas;
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @author lenovo-pc
 */
public class TarHandler implements Runnable {

	static org.apache.log4j.Logger logger = null;

	static {
		logger = org.apache.log4j.Logger.getLogger(TarHandler.class.getName());
	}
	ThreadPoolExecutor threadpool;

	public TarHandler() {
		threadpool = new ThreadPoolExecutor(6, 6, 3, TimeUnit.SECONDS,
			new LinkedBlockingQueue<Runnable>(100),
			new ThreadFactory() {
				AtomicInteger idx = new AtomicInteger(0);

				@Override
				public Thread newThread(Runnable r) {
					return new Thread(r, "JsonTarTask_" + idx.getAndIncrement());
				}
			}, new RejectedExecutionHandler() {

				@Override
				public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
					while (true) {
						try {
							executor.getQueue().put(r);
							break;
						} catch (InterruptedException ex) {
							logger.warn("", ex);
						}
					}
				}
			});
	}

	@Override
	public void run() {
		logger.info("The uncompress gzFile is running!");
		ArrayList<String> fileList = new ArrayList<String>(50);
		while (true) {
			try {
				String str = GlobalParas.untarQueue.poll(500, TimeUnit.MILLISECONDS);
//				if (str == null) {
//					break;
//				}
				if (str == null || str.isEmpty() || str == "") {
					Thread.sleep(5000);
				} else if (!str.isEmpty() && str != null && str != "") {
					threadpool.execute(new TarTask(str));
				}
			} catch (Exception ex) {
				logger.error("this unzip  threadpool error :" + ex, ex);

			}
		}
	}

}
